package com.credithc.customers.base.utils;

/**
 * @Title: 密码加密工具类
 * @Author: Denghx
 * @Date: 2019/6/4 1:28
 * @Description: com.credithc.customers.base.utils
 * @Version: V1.0.0
 */

import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

public class EncryptUtils {
    public static final String MD5 = "MD5";
    public static final String SHA1 = "SHA1";
    public static final String SHA1_SALT_HYR = "xxxxxxx";
    public static final String SHA1_SALT_YZT = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * 编码格式；默认使用uft-8
     */
    public String charset = "utf-8";


    /**
     * @description: 恒慧融出借端加密算法
     * @author: denghx
     * @date: 2019/6/4 11:35
     * @param: inStr
     * @return: java.lang.String
     */
    public static String getHhrcfMd5(String pwd) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance(MD5);
        } catch (Exception e) {
            //log.warn("md5 not supported", e);
        }
        // 字符串反转
        StringBuilder sb = new StringBuilder(pwd.trim());
        String reverseStr = sb.reverse().toString();
        char[] charArray = reverseStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        if (md5 == null) {
            return "";
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = (md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static String getHhrjkMd5(String pwd) {
        boolean isUpper = false;
        Integer bit = 32;
        String md5 = new String();
        try {
            // 创建加密对象
            MessageDigest md = MessageDigest.getInstance(MD5);
            if (bit == 64) {
                BASE64Encoder bw = new BASE64Encoder();
                String bsB64 = bw.encode(md.digest(pwd.getBytes("utf-8")));
                md5 = bsB64;
            } else {
                // 计算MD5函数
                md.update(pwd.getBytes());
                byte b[] = md.digest();
                int i;
                StringBuffer sb = new StringBuffer("");
                for (int offset = 0; offset < b.length; offset++) {
                    i = b[offset];
                    if (i < 0) {
                        i += 256;
                    }
                    if (i < 16) {
                        sb.append("0");
                    }
                    sb.append(Integer.toHexString(i));
                }
                md5 = sb.toString();
                if (bit == 16) {
                    //截取32位md5为16位
                    String md16 = md5.substring(8, 24).toString();
                    md5 = md16;
                    if (isUpper) {
                        md5 = md5.toUpperCase();
                    }
                    return md5;
                }
            }
            //转换成大写
            if (isUpper) {
                md5 = md5.toUpperCase();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("md5加密抛出异常！");
        }

        return md5;
    }

    /**
     * @description: 恒易融密码加密 标准sha1加密(加盐SHA1_SALT)，可碰撞破解
     * @author: denghx
     * @date: 2019/6/4 18:44
     * @param: s
     * @return: java.lang.String
     */
    public static String getHyrjkSha1(String pwd) {
        if (null == pwd || 0 == pwd.length()) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(SHA1);
            mdTemp.update((pwd + SHA1_SALT_HYR).getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 一账通加密
     *
     * @param pwd 要加密的字符串
     * @return 加密后的字符串
     */
    public static String getYztSha1(String pwd) {
        BigInteger sha = null;
        byte[] bys = (pwd + SHA1_SALT_YZT).getBytes();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(SHA1);
            messageDigest.update(bys);
            sha = new BigInteger(messageDigest.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sha.toString(32);
    }

    /**
     * 字符串+随机盐 sha加密
     *
     * @param s 要加密的字符串
     * @return 盐和加密后的字符串
     */
    public static Map<String, String> getResult(String s) {
        Map<String, String> map = new HashMap<String, String>();
        String salt = getSalt();
        map.put("salt", salt);//盐
        map.put("password", getYztSha1(s + salt));//加密后的密码
        return map;
    }

    /**
     * 生成随机盐
     *
     * @return 随机生成的盐
     */
    private static String getSalt() {
        SecureRandom random = new SecureRandom();
        int length = random.nextInt(5) + 8;//盐的长度，这里是8-12可自行调整
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = SHA1_SALT_YZT.charAt(random.nextInt(SHA1_SALT_YZT.length()));
        }
        return new String(text);
    }

    /**
     * @description: 标准sha1加密
     * @author: fby
     * @date: 2020/3/3 13:42
     * @param: s
     * @return: java.lang.String
     */
    public static String getSha1(String pwd) {
        if (null == pwd || 0 == pwd.length()) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(SHA1);
            mdTemp.update((pwd).getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 测试方法
     *
     * @param args
     */
    public static void main(String[] args) {
        /*String s = "{\"resCode\":\"1012\",\"resMsg\":\"参数为空或格式错误\",\"tid\":null,\"sign\":null}";
        String[] d = s.split("\"");
        for (String s1 : d) {
            System.out.println(s1);
        }*/
        System.out.println(getSha1("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALoi2dnIAXpPmHeDo/VzvGBNc6wwpACF+fhc/4G6hjUUg//aBED99BIZnqc/GwrtvB5ViWffq9sSmlkmSnvCyu+AVE1YoJ2iSIWeIliWEMrYKWvzEHeAQhl8qxB0+wPZCQZt4+qPstzXzwCNa2+J8ToOLUTPsiZhJBy18pTXFMD1AgMBAAECgYArU6dwCR1G8jYkQ7ErlkgYBo9RWnUiZg08obEb6mYI/wCG0qHA2xwwBmSmu4q47YOnb/OvCSKAuQDSlZYq3rnLxkivbgafP+u1h2f+0LWVbHvumi8OcVLQNfjta7"));
    }


}
